const {ccclass, property} = cc._decorator;

@ccclass
export default class JoinGameInput extends cc.Component{

    /**
     * 输入房间号的输入框数组
     */
    @property([cc.Label])
    nums: cc.Label[] = [];

    /**
     * 输入位置标记
     */
    inputIndex = 0;

    onLoad(){
        
    }

    onEnable(){
        this.onResetClicked();
    }

    /**
     * 重置输入框
     */
    onResetClicked(){
        this.nums.map((value, index) => {
            value.string = '';
        });
        this.inputIndex = 0;
    }

    /**
     * 输入0
     */
    onN0Clicked(){
        this.onInput(0);
    }
    /**
     * 输入1
     */
    onN1Clicked(){
        this.onInput(1);
    }
    /**
     * 输入2
     */
    onN2Clicked(){
        this.onInput(2);
    }
    /**
     * 输入3
     */
    onN3Clicked(){
        this.onInput(3);
    }
    /**
     * 输入4
     */
    onN4Clicked(){
        this.onInput(4);
    }
    /**
     * 输入5
     */
    onN5Clicked(){
        this.onInput(5);
    }
    /**
     * 输入6
     */
    onN6Clicked(){
        this.onInput(6);
    }
    /**
     * 输入7
     */
    onN7Clicked(){
        this.onInput(7);
    }
    /**
     * 输入8
     */
    onN8Clicked(){
        this.onInput(8);
    }
    /**
     * 输入9
     */
    onN9Clicked(){
        this.onInput(9);
    }

    /**
     * 输入房间号的监控逻辑
     * @param num 
     */
    onInput(num: number){
        if(this.inputIndex >= this.nums.length){
            return;
        }
        this.nums[this.inputIndex].string = num.toString();
        this.inputIndex++;

        if(this.inputIndex == this.nums.length){
            let roomId = this.parseRoomID();
            console.log('%c输入的房间号是：' + roomId, cc.vv.logStyle);
            this.onInputFinished(roomId);
        }
    }


    /**
     * 连接房间号
     */
    parseRoomID(){
        return this.nums.reduce((pre, cur) => {
           return pre + cur.string;
        }, '');
    }


    /**
     * 进入房间
     */
    onInputFinished(roomId){
        cc.vv.userMgr.entryRoom(roomId, (ret) => {
            if(ret.errcode == 0){
                this.node.active = false;
            }
            else{
                let content = `房间"${roomId}"不存在，请重新输入！`;
                if(ret.errcode == 4){
                    content = `房间"${roomId}"已满`;
                }
                cc.vv.alert.show('提示', content);
                this.onResetClicked();
            }
        });
    }


    /**
     * 撤销上一次输入
     */
    onDelClicked(){
        if(this.inputIndex > 0){
            this.inputIndex--;
            this.nums[this.inputIndex].string = '';
        }
    }

    /**
     * 关闭输入框
     */
    onCloseClicked(){
        this.node.active = false;
    }
}